package com.util;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WechatSignatureUtil {

	/**
	 * 
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	 * @param token
	 * @param timestamp
	 * @param nonce
	 * @param wechatSignature
	 * @return
	 */
	public static boolean checkWechatSignature(String token, String timestamp,
			String nonce, String wechatSignature) {

		String[] arrTmp = { token, timestamp, nonce };
		Arrays.sort(arrTmp);
		StringBuffer sb = new StringBuffer();
		// 2.将三个参数字符串拼接成一个字符串进行sha1加密
		for (int i = 0; i < arrTmp.length; i++) {
			sb.append(arrTmp[i]);
		}

		String my_signature = HashEncoder.encode(HashEncoder.SHA1, sb.toString());

		System.out.println("source code: "+sb.toString());
		System.out.println("my_signature: "+my_signature);
		System.out.println("wechatSignature: "+wechatSignature);
		
		if (my_signature.equals(wechatSignature)) {
			System.out.println("signature check success");
			return true;
		} else {
			System.out.println("signature check fail");
			return false;
		}

	}
	
}
